/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 * tkurz
 *
 * File Info:
 * User: tkurz
 * Date: 2011/01/17
 * Time: 13:02
 *
 * Project: KiWi2, kiwi-core module
 */

package kiwi.core.services.io;

import kiwi.core.api.io.KiWiSerializer;
import kiwi.core.model.rdf.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;

import javax.inject.Inject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * The KiWi RdfJsonSerializer takes as argument a collection of triples and serialises them in the
 * RDF/JSON format like described in http://n2.talis.com/wiki/RDF_JSON_Specification.
 * <p>
 * In general, a triple (Subject, Property, Object) is encoded in the following structure:
 * { "S" : { "P" : [ O ] } }
 * The object of the triple O is represented as a further JSON object with the following keys:
 * <ul>
 * <li>type: one of 'uri', 'literal' or 'bnode' (required and must be lowercase)
 * <li>value: the lexical value of the object (required, full URIs should be used, not qnames)
 * <li>lang: the language of a literal value (optional but if supplied it must not be empty
 * <li>datatype: the datatype URI of the literal value (optional)
 * </ul>
 * The 'lang' and 'datatype' keys should only be used if the value of the 'type' key is "literal".
 * User: Thomas Kurz
 * Date: 17.01.11
 * Time: 13:02
 */
public class RdfJsonSerializer implements KiWiSerializer {

	@Inject
    private Logger log;

	private static final String VALUE = "value";
	private static final String TYPE = "type";
	private static final String BNODE = "bnode";
	private static final String URI = "uri";
	private static final String LITERAL = "literal";
	private static final String LANG = "lang";
	private static final String DATATYPE = "datatype";

	private static final List<String> MIMETYPES;
	static {
		MIMETYPES = new ArrayList<String>();
		MIMETYPES.add("application/json");
	}

	@Override
	public List<String> getProducedFormats() {
		return MIMETYPES;
	}

    @Override
    public String serializeTriples(Iterable<KiWiTriple> triples) {
		try {
			StringWriter w = new StringWriter();
			serializeTriples(triples, w);
			return w.toString();
		} catch (IOException e) {
			log.error("IO exception while writing output stream",e);
			return null;
		}
    }

    @Override
    public void serializeTriples(Iterable<KiWiTriple> triples, OutputStream out) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(out,serialize(triples));
    }

    @Override
    public void serializeTriples(Iterable<KiWiTriple> triples, Writer writer) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer,serialize(triples));
    }

	/**
	 * This method wraps triples (Subject,Property,Object) in a dataformat that is serializable
	 * by Jackson (namely maps and sets).
	 * @param triples
	 * @return
	 */
    private Object serialize(Iterable<KiWiTriple> triples) {

        HashMap<String,HashMap<String,HashSet<HashMap<String,String>>>> subjects = new HashMap<String,HashMap<String,HashSet<HashMap<String,String>>>>();
        for( KiWiTriple triple : triples ) {

            // get subject key
			String subjectKey;
			if( triple.getSubject().isUriResource() ) {
				subjectKey = ((KiWiUriResource)triple.getSubject()).getUri();
			} else {
				subjectKey = ((KiWiAnonResource)triple.getSubject()).getAnonId();
			}

			//add or get predicate map
			HashMap<String,HashSet<HashMap<String,String>>> predicates;
            if( subjects.containsKey(subjectKey)) {
                predicates = subjects.get(subjectKey);
            } else {
                predicates = new HashMap<String,HashSet<HashMap<String,String>>>();
                subjects.put(subjectKey,predicates);
            }

            //get predicate key
            String predicateKey = triple.getProperty().getUri();

			//add or get object set
			HashSet<HashMap<String,String>> objects;
            if( predicates.containsKey(predicateKey) ) {
				objects = predicates.get(predicateKey);
			} else {
		 		objects = new HashSet<HashMap<String,String>>();
				predicates.put(predicateKey,objects);
			}

			//add objects
			HashMap<String,String> object = new HashMap<String,String>();
			KiWiNode objectNode = triple.getObject();
			if( objectNode.isLiteral() ) {
				object.put(TYPE,LITERAL);
				object.put(VALUE,((KiWiLiteral)objectNode).getContent());
				if(((KiWiLiteral) objectNode).getLanguage() != null )
					object.put(LANG,((KiWiLiteral) objectNode).getLanguage().getLanguage());
				if(((KiWiLiteral) objectNode).getType() != null)
					object.put(DATATYPE,((KiWiLiteral) objectNode).getType());
			} else {
				if( objectNode.isUriResource() ) {
					object.put(TYPE,URI);
					object.put(VALUE,((KiWiUriResource)objectNode).getUri());
				} else {
					object.put(TYPE,BNODE);
					object.put(VALUE,((KiWiAnonResource)objectNode).getAnonId());
				}
			}
			objects.add(object);

        }
        return subjects;
    }

}
